package com.edu.backend.config;

import com.edu.backend.utils.JwtUtils;
import com.edu.backend.utils.R;
import com.edu.backend.utils.ResponseUtil;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Enumeration;

/**
 * @Author: yanjunfeng
 * @Description: TODO
 * @Date: Created in 上午7:28 2023/6/20
 * @Modified By:
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        String token = request.getHeader("token");
        Enumeration headerNames=request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            System.out.println(headerName + " : " + request.getHeader(headerName) + "<br />");
        }
        System.out.println("LoginInterceptor-"+token);
        if (token == null) {
            System.out.println("code-"+5008);
            ResponseUtil.out(response, R.error().code(5008).message("未登录"));
            return false;
        }
        if (!JwtUtils.checkToken(token)) {
            ResponseUtil.out(response, R.error().code(50014).message("登录失效"));
            return false;
        }
        return true;


    }
}

